package com.nexus.service.sys.service;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nexus.core.exception.ServiceException;
import com.nexus.core.service.BaseService;
import com.nexus.core.sys.entity.SysLog;
import com.nexus.core.sys.entity.SysMessage;
import com.nexus.service.sys.mapper.SysMessageMapper;
import com.nexus.core.sys.dto.SysMessageDTO;
import com.nexus.service.sys.service.mapstruct.SysMessageWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 系统消息Service
 * @author yf
 * @version 2023-06-30
 */
//@DS("zxhy_platform_db")
//@Service
@Transactional(rollbackFor = {ServiceException.class,Exception.class, RuntimeException.class})
public class SysMessageService extends BaseService<SysMessageMapper, SysMessage, SysMessageDTO,SysMessageWrapper> {

    
    @Autowired
	private SysMessageWrapper sysMessageWrapperImpl;

	/**
	 * 根据id查询
	 * @param id
	 * @return
	 */
	public SysMessageDTO findById(String id) {
		return baseMapper.findById ( id );
	}

	/**
	 * 自定义分页检索
	 * @param page
	 * @param queryWrapper
	 * @return
	 */
	public IPage <SysMessageDTO> findPage(Page <SysMessageDTO> page, QueryWrapper queryWrapper,String userId) {
		//queryWrapper.eq ("a.deleted", 0 ); // 排除已经删除
		IPage<SysMessageDTO> list = baseMapper.findList(page, queryWrapper);
		return  list;
	}

	public long countNoRead(String userId){
		return this.count(new QueryWrapper<SysMessage>().eq("status", "0").eq("receive_user",userId));
	}


	/**
	 * 更新已读
	 * @param id
	 */
	public void updateStatus(List id,String userId){
		UpdateWrapper<SysMessage> updateWrapper = new UpdateWrapper<>();
		if(CollectionUtils.isNotEmpty(id)){
			updateWrapper.in("id",id);
		}else{
			updateWrapper.eq("receive_user",userId);
		}
		updateWrapper.set("status","1");
		updateWrapper.set("receive_time",new Date());
		this.update(updateWrapper);
	}

	/**
	 * 是否已插入
	 * @param selfCode
	 * @return
	 */
	public boolean isSelfCode(String selfCode){
		QueryWrapper<SysMessage> queryWrapper = new QueryWrapper();
		queryWrapper.eq("relation_id", selfCode);
		List<SysMessage> list = this.list(queryWrapper);
		if(CollectionUtil.isNotEmpty(list)){
			return true;
		}else{
			return false;
		}
	}
}
